package com.siyoumi.app.modules.book.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.annotation.RequestLimit;
import com.siyoumi.app.entity.Book;
import com.siyoumi.app.entity.BookRecord;
import com.siyoumi.app.entity.BookSku;
import com.siyoumi.app.entity.BookSkuDay;
import com.siyoumi.app.modules.book.entity.BookInfo;
import com.siyoumi.app.modules.book.service.SvcBook;
import com.siyoumi.app.modules.book.service.SvcBookSku;
import com.siyoumi.app.modules.book.service.SvcBookSkuDate;
import com.siyoumi.app.modules.book.vo.VaBookCancel;
import com.siyoumi.app.modules.book.vo.VaBookSumbit;
import com.siyoumi.app.modules.book.vo.VaBookUse;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.app.service.BookRecordService;
import com.siyoumi.app.service.BookService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wxapp/book/api")
public class ApiBook
        extends WxAppApiController {
    //预约列表
    @GetMapping({"book_list"})
    public XReturn bookList() {
        InputData inputData = InputData.fromRequest();
        String type = input("type");

        String[] select = {
                "book_id",
                "book_name",
                "book_hide",
                "book_pic",
                "book_date_begin",
                "book_date_end",
                "book_order",
        };
        JoinWrapperPlus<Book> query = SvcBook.getBean().listQuery(inputData);
        query.eq("book_hide", 0);
        query.select(select);
        //
        if (XStr.hasAnyText(type)) { //类型
            switch (type) {
                case "0": //已过期
                    query.le("book_date_end", LocalDateTime.now());
                    break;
                case "1": //进行中
                    query.gt("book_date_end", LocalDateTime.now());
                    break;
            }
        }

        //list
        IPage<Book> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        IPage<Map<String, Object>> pageData = SvcBook.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        for (Map<String, Object> item : list) {
        }

        getR().setData("list", list);

        return getR();
    }

    //预约信息
    @GetMapping({"book_info"})
    public XReturn bookInfo() {
        InputData inputData = InputData.fromRequest();
        String bookId = inputData.input("book_id");

        if (XStr.isNullOrEmpty(bookId)) {
            return XReturn.getR(20087, "miss book_id");
        }

        Book entityBook = SvcBook.getApp().first(bookId);
        Map<String, Object> mapBook = entityBook.toMap();
        mapBook.put("book_can", SvcBook.getBean().bookCan(entityBook.getBook_id(), getOpenid()));
        //开始倒计时
        mapBook.put("begin_left_s", XDate.leftSeconds(LocalDateTime.now(), entityBook.getBook_date_begin()));
        //结束倒计时
        mapBook.put("end_left_s", XDate.leftSeconds(LocalDateTime.now(), entityBook.getBook_date_end()));
        mapBook.put("info", SvcBook.getBean().getInfo(entityBook.getBook_info_json()));
        //总人数
        mapBook.put("stock_total", SvcBook.getBean().getStockTotal(entityBook.getBook_id()));

        //用户积分
        Long leftFun = SvcFun.getBean().getFun(getOpenid());


        getR().setData("left_fun", leftFun);
        getR().setData("book", mapBook);

        return getR();
    }

    //预约日期列表
    @GetMapping({"book_day_list"})
    public XReturn bookDayList() {
        InputData inputData = InputData.fromRequest();
        String bookId = inputData.input("book_id");

        if (XStr.isNullOrEmpty(bookId)) {
            return XReturn.getR(20087, "miss book_id");
        }

        List<String> weeks = XApp.getWeeks();

        //最多显示1年数据
        JoinWrapperPlus<BookSkuDay> query = SvcBookSkuDate.getBean().listQuery();
        query.select("bday_date");
        query.eq("bday_book_id", bookId)
                .ge("bday_date", XDate.today())
                .lt("bday_date", XDate.today().plusDays(365))
        ;
        query.groupBy("bday_date");
        query.orderByAsc("bday_date");
        List<Map<String, Object>> list = SvcBookSkuDate.getApp().getMaps(query);
        for (Map<String, Object> item : list) {
            LocalDateTime date = (LocalDateTime) item.get("bday_date");
            int weekIndex = date.toLocalDate().getDayOfWeek().getValue();
            item.put("week", weekIndex);
            item.put("week_str", weeks.get(weekIndex - 1));
            item.put("bday_date", XDate.toDateString(date));
        }

        getR().setData("list", list);
        return getR();
    }

    //预约sku列表
    @GetMapping({"book_sku_list"})
    public XReturn bookSkuList() {
        InputData inputData = InputData.fromRequest();
        String bookId = inputData.input("book_id");
        String date = inputData.input("date");
        if (XStr.isNullOrEmpty(bookId)) {
            return XReturn.getR(20087, "miss book_id");
        }
        if (XStr.isNullOrEmpty(date)) {
            return XReturn.getR(20089, "miss date");
        }

        String[] select = {
                "bday_id",
                "bday_date",
                "bday_sku_id",
                "stock_count_left",
                "stock_count_use",
                "bday_before_enable",
                "bday_before_time",
                "bday_append_max",
                "bsku_id",
                "bsku_name",
                "bsku_before_time",
                "bsku_order",
        };
        JoinWrapperPlus<BookSkuDay> query = SvcBookSkuDate.getBean().listQuery();
        query.join(BookSku.table(), BookSku.tableKey(), "bday_sku_id");
        query.eq("bday_book_id", bookId)
                .eq("bday_date", date)
                .eq("bsku_hide", 0)
        ;
        query.orderByAsc("bsku_order")
                .orderByDesc("bsku_create_date");
        query.select(select);
        List<Map<String, Object>> list = SvcBookSkuDate.getApp().getMaps(query);
        for (Map<String, Object> item : list) {
            BookSkuDay entity = SvcBookSkuDate.getApp().loadEntity(item);
            BookSku entitySku = SvcBookSku.getApp().loadEntity(item);

            //截止时间
            Long m = entitySku.getBsku_before_time();
            if (entity.getBday_before_enable() == 1) {
                //日期特殊设置
                m = entity.getBday_before_time();
            }

            LocalDateTime dateTimeEnd = SvcBookSku.getBean().getDateTimeEnd(entitySku
                    , XDate.toDateString(entity.getBday_date())
                    , m);
            Long leftSeconds = XDate.leftSeconds(LocalDateTime.now(), dateTimeEnd);
            item.put("left_second", leftSeconds); //离结束剩下秒数
        }

        getR().setData("list", list);
        return getR();
    }

    //能否预约
    @GetMapping({"book_submit_can"})
    public XReturn bookSubmitCan() {
        InputData inputData = InputData.fromRequest();
        String dayId = inputData.input("day_id");

        VaBookSumbit vo = new VaBookSumbit();
        vo.setDay_id(dayId);

        return SvcBook.getBean().bookSubmitCan(vo);
    }

    //预约
    @RequestLimit(second = 20)
    @PostMapping({"book_submit"})
    public XReturn bookSubmit(@Validated @RequestBody VaBookSumbit vo, BindingResult result) {
        //通用验证
        XValidator.getResult(result, true, true);

        return SvcBook.getBean().bookSubmit(vo);
    }

    //我的预约列表
    @GetMapping({"user_book_list"})
    public XReturn userBookList() {
        InputData inputData = InputData.fromRequest();
        String type = inputData.input("type");

        String[] select = {
                "book_id",
                "book_name",
                "book_pic",
                "book_hide",
                "brecord_id",
                "brecord_state",
                "brecord_use",
        };
        JoinWrapperPlus<BookRecord> query = SvcBook.getBean().listRecordQuery(null, inputData);
        query.join(Book.table(), Book.tableKey(), "brecord_book_id");
        query.eq("brecord_wxuser_id", getOpenid())
                .ne("brecord_state", -1)
                .eq("brecord_cancel", 0)
                .isNull("brecord_pid");
        ;
        query.orderByDesc("brecord_create_date");
        query.select(select);
        //
        if (XStr.hasAnyText(type)) { //类型
            switch (type) {
                case "0": //待审核
                    query.eq("brecord_state", 0);
                    break;
                case "1": //已通过
                    query.eq("brecord_state", 1);
                    break;
            }
        }
        IPage<BookRecord> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = BookRecordService.getBean().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        for (Map<String, Object> item : list) {
        }

        getR().setData("list", list);

        return getR();
    }

    //我的预约详情
    @GetMapping({"user_book_info"})
    public XReturn userBookInfo() {
        InputData inputData = InputData.fromRequest();
        String recordId = inputData.input("record_id");
        if (XStr.isNullOrEmpty(recordId)) {
            return XReturn.getR(20339, "缺少预约ID");
        }

        String[] select = {
                "t_book_record.*",
                "book_id",
                "book_name",
                "book_info_json",
                "book_audit_enable",
                "bsku_name",
                "bday_date",
        };
        JoinWrapperPlus<BookRecord> query = BookRecordService.getBean().join();
        query.join(Book.table(), Book.tableKey(), "brecord_book_id");
        query.join(BookSkuDay.table(), BookSkuDay.tableKey(), "brecord_bday_id");
        query.join(BookSku.table(), BookSku.tableKey(), "bday_sku_id");
        query.select(select);
        query.eq("brecord_id", recordId);
        Map<String, Object> mapRecord = BookRecordService.getBean().firstMap(query);
        if (mapRecord == null) {
            return XReturn.getR(20349, "预约ID异常");
        }

        BookRecord entityRecord = BookRecordService.getBean().loadEntity(mapRecord);

        //预约信息
        Book entityBook = BookService.getBean().loadEntity(mapRecord);
        //
        BookInfo info = SvcBook.getBean().getInfo(entityBook.getBook_info_json());
        mapRecord.put("book_info_json", info);

        //同行人订单
        JoinWrapperPlus<BookRecord> queryAppend = SvcBook.getBean().listRecordAppendQuery(entityRecord.getBrecord_id());
        queryAppend.select("brecord_name", "brecord_phone", "brecord_idcard");
        queryAppend.eq("brecord_pid", entityRecord.getBrecord_id());
        List<Map<String, Object>> listAppend = BookRecordService.getBean().getMaps(queryAppend);


        getR().setData("record", mapRecord);
        getR().setData("append", listAppend);

        return getR();
    }

    /**
     * 预约核销
     */
    @PostMapping({"book_use"})
    public XReturn bookUse(@Validated VaBookUse vo, BindingResult result) {
        //通用验证
        XValidator.getResult(result, true, true);

        return SvcBook.getBean().bookUse(vo);
    }


    /**
     * 预约取消
     */
    @PostMapping({"book_cancel"})
    public XReturn bookCancel(@Validated VaBookCancel vo, BindingResult result) {
        //通用验证
        XValidator.getResult(result, true, true);

        return SvcBook.getBean().bookCancel(vo);
    }
}
